package org.zxb.demo.resolver;

import lombok.NoArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.web.multipart.MultipartFile;
import org.zxb.demo.annotation.MultipartFileVerify;

/**
 * 文件类型校验-文件大小限制
 *
 * @author zxb
 * @date 2022-04-08 10:00
 **/
@Log4j2
@NoArgsConstructor
public class MultipartFileMaxSizeValidator extends AbstractMultipartFileValidator {

    protected AbstractMultipartFileValidator delegate;

    public MultipartFileMaxSizeValidator(AbstractMultipartFileValidator abstractMultipartFileValidator) {
        delegate = abstractMultipartFileValidator;
    }

    @Override
    public boolean isFileValid(MultipartFileVerify multipartFileValid, MultipartFile value) {
        if (value.isEmpty()) {
            log.warn("upload file is empty.");
            return false;
        }
        // 1. 如果没有配置文件大小限制，则不校验
        // 2. 如果没有超过限制，则校验通过；千字节转字节 * 1024
        if (multipartFileValid.maxSize() < 0 || value.getSize() <= multipartFileValid.maxSize() * 1024L) {
            return delegate.isFileValid(multipartFileValid, value);
        }
        log.warn("文件大小超过限制，文件名：{}，文件大小：{} Byte", value.getOriginalFilename(), value.getSize());
        return false;
    }
}
